import json
import tornado.ioloop
import tornado.options
from tornado.websocket import WebSocketHandler
from tornado.web import Application, RequestHandler
import pymongo


class Receiver(WebSocketHandler):
    callbacks = []
    db = pymongo.MongoClient().test.test

    def open(self):
        self.callbacks.append(self.callback)
        print("WebSocket opened")

    def on_message(self, message):
        m = json.loads(message)
        # self.db.insert(m)
        print('recieve: %s' % message)

    def on_close(self):
        self.callbacks.remove(self.callback)
        print("WebSocket closed")

    def callback(self, msg):
        self.write_message(msg)


class NewTask(RequestHandler):
    def get(self):
        self.render('task.html')

    def post(self):
        id = self.get_body_argument('taskid')
        optype = self.get_body_argument('optype')
        url = self.get_body_argument('url')
        msg = dict(id=id, optype=optype, url=url)
        msg_dict = json.dumps(msg)
        for callback in Receiver.callbacks:
            callback(msg_dict)


if __name__ == "__main__":
    app = tornado.web.Application(handlers=[(r'/websocket', Receiver), (r'/newtask', NewTask)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()
